/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.daydream.template.sequence.segment;

import org.apache.commons.lang3.StringUtils;
import org.pajamas.protocol.Serializer;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import lombok.Getter;

/**
 * @author william
 * @since 2024/4/3
 */
@Getter
public class SegmentDefinition {
    private final Serializer valueSerializer;
    private final String key;
    private final String defaultValue;

    private SegmentDefinition(Serializer valueSerializer, String key, String defaultValue) {
        this.valueSerializer = valueSerializer;
        this.key = key;
        this.defaultValue = defaultValue;
    }

    @Nonnull
    public static Builder newBuilder() {
        return new Builder();
    }

    public String toString(@Nullable Object value) {
        return StringUtils.firstNonBlank(this.valueSerializer.stringify(value), this.defaultValue);
    }

    @Override
    public String toString() {
        return this.toString(null);
    }

    public static class Builder implements org.pajamas.protocol.Builder<SegmentDefinition> {
        private Serializer valueSerializer;
        private String key;
        private String defaultValue;

        private Builder() {
        }

        public Builder valueSerializer(Serializer valueSerializer) {
            this.valueSerializer = valueSerializer;
            return this;
        }

        public Builder key(String key) {
            this.key = key;
            return this;
        }

        public Builder defaultValue(String defaultValue) {
            this.defaultValue = defaultValue;
            return this;
        }

        @Override
        public SegmentDefinition build() {
            return new SegmentDefinition(this.valueSerializer, this.key, this.defaultValue);
        }
    }
}
